<template>
  <div style="padding: 10px; margin-bottom: 50px">
    <el-row>
      <el-col :span="4">
        <el-card style="width: 250px; height: 450px; color: #333">
          <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">
            家政公司列表<span style="font-size: 12px"
          </div>
          <div style="padding: 10px 0" v-for="user in users" :key="user.fromId">
            <span
              ><el-badge
                :hidden="user.count == 0"
                :value="user.count"
                class="item"
              >
                <el-button
                  style="width: 210px"
                  @click="
                    chatUser = user.fromId;
                    chatUsername = user.fromName
                    user.count = 0;
                    showMessage(user.fromId);
                  "
                  size="small"
                  >{{ user.fromName
                  }}<span
                    style="font-size: 12px; color: limegreen; margin-left: 5px"
                    v-if="user.fromId === chatUser"
                    >chatting...</span
                  ></el-button
                >
              </el-badge></span
            >
          </div>
        </el-card>
      </el-col>

      <el-col :span="20">
        <div
          style="
            width: 800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 0 10px #ccc;
          "
        >
          <div style="text-align: center; line-height: 50px">
            {{ chatUsername }}
          </div>
          <div
            style="height: 350px; overflow: auto; border-top: 1px solid #ccc"
            v-html="content"
          ></div>
          <div style="height: 60px">
            <textarea
              v-model="text"
              style="
                height: 60px;
                width: 95%;
                padding: 20px;
                border: none;
                border-top: 1px solid #ccc;
                border-bottom: 1px solid #ccc;
                outline: none;
                resize:none;
              "
            ></textarea>
            <div style="text-align: right; padding-right: 10px">
              <el-button type="primary" v-if="!human" size="mini" @click="tohuman()"
                >转人工</el-button
              >
              <el-button type="primary" size="mini" @click="send()"
                >发送</el-button
              >
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
let socket;
import Cookie from "js-cookie";
export default {
  name: "Im",
  data() {
    return {
      user: {},
      isCollapse: false,
      users: [],
      chatUser: "",
      text: "",
      messages: [],
      content: "",
      chatUsername: "",
      human:false,
    };
  },
  created() {
    this.getmessage();
    // this.init()
  },
  methods: {
    showMessage(companyId) {
      if(socket != null){
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
      }
      this.content = "";
      this.human = false
      let userid = Cookie.get("userid");
      let _this = this;
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        let socketUrl =
          "ws://8.130.52.6:8082/chat/USER/" + userid + "/" + companyId;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {};
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data);
          let data = JSON.parse(msg.data); // 对收到的json数据进行解析， 类似这样的： {"users": [{"userid": "zhang"},{ "userid": "admin"}]}

          //  // {"from": "zhang", "text": "hello"}
            _this.messages.push(data);
            // 构建消息内容
            if(data.origin == 'COMPANY'){
              _this.createContent(data.fromId, null, data.text, data.tip);
            }else{
              _this.createContent(null, data.toId, data.text, data.tip);
            }
        };
        //关闭事件
        // socket.onclose = function () {
        //   console.log("websocket已关闭");
        // };
        // //发生了错误事件
        // socket.onerror = function () {
        //   console.log("websocket发生了错误");
        // };
      }
    },
    getmessage() {
      this.axios
        .get("api/user/auth/chat/listUserCount")
        .then((response) => {
          this.users = response.data.value;
          if(Cookie.get('chatCompany')){
            var chatCompany = JSON.parse(Cookie.get('chatCompany'))
            var is = false
            for(var i=0;i<this.users.length;i++){
              if(chatCompany.fromId == this.users[i].fromId){
                is = true
              }
            }
            if(!is){
              this.users.splice(0,0,chatCompany);
            }
            // if(this.users.)
            // this.users.push()
          }
        })
        .catch((error) => {});
    },
    send() {
      if (!this.chatUser) {
        this.$message({ type: "warning", message: "请选择聊天对象" });
        return;
      }
      if (!this.text) {
        this.$message({ type: "warning", message: "请输入内容" });
      } else {
        if (typeof WebSocket == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          // 组装待发送的消息 json
          // {"from": "zhang", "to": "admin", "text": "聊天文本"}
          let message = {
            text: this.text,
            human: this.human,
          };
          socket.send(JSON.stringify(message)); // 将组装好的json发送给服务端，由服务端进行转发
          this.messages.push({ user: Cookie.get("userid"), text: this.text });
          // 构建消息内容，本人消息
          this.createContent(null, Cookie.get("userid"), this.text);
          this.text = "";
        }
      }
    },
    createContent(remoteUser, nowUser, text, istip) {
      
      // 这个方法是用来将 json的聊天消息数据转换成 html的。
      let html;
      // 当前用户消息
      if (nowUser) {
        console.log(text)
        // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
        html =
          '<div class="el-row" style="padding: 5px 0">\n' +
          '  <div class="el-col el-col-22" style="text-align: right; padding-right:10px">\n' +
          '    <div class="tip left" style="margin-top:12px">' +
          text +
          "</div>\n" +
          "  </div>\n" +
          '  <div class="el-col el-col-2">\n' +
          '  <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">\n' +
          '    <img src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" style="object-fit: cover;">\n' +
          "  </span>\n" +
          "  </div>\n" +
          "</div>";
      } else if (remoteUser) {
        // remoteUser表示远程用户聊天消息，蓝色的气泡
        if (!istip) {
          html =
            '<div class="el-row" style="padding: 5px 0">\n' +
            '  <div class="el-col el-col-2" style="text-align: right">\n' +
            '  <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">\n' +
            '    <img src="https://storage-public.zhaopin.cn/user/avatar/1588585975123306833/wx_1_avatar_female_2.d642fb43f32b5deca8165cc037005cab.png" style="object-fit: cover;">\n' +
            "  </span>\n" +
            "  </div>\n" +
            '  <div class="el-col el-col-22" style="text-align: left; padding:10px 0 0 10px">\n' +
            '    <div class="tip right">' +
            text +
            "</div>\n" +
            "  </div>\n" +
            "</div>";
        } else {
          html =
            "<div style='border: 1px solid #f0f4fd;width:500px;height:30px;margin-left:150px;border-radius: 5px; background-color: #f0f4fd;'><p style='text-align: center;margin-top:6px'>" +
            text +
            "</p> </div>";
        }
      }
      this.content += html;
    },
    init() {
      let userid = Cookie.get("userid");
      console.log(userid);
      let _this = this;
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://8.130.52.6:8082/chat/" + userid;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data);
          let data = JSON.parse(msg.data); // 对收到的json数据进行解析， 类似这样的： {"users": [{"userid": "zhang"},{ "userid": "admin"}]}
          if (data.users) {
            // 获取在线人员信息
            _this.users = data.users.filter((user) => user.userid !== userid); // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
          } else {
            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            //  // {"from": "zhang", "text": "hello"}
            if (data.from === _this.chatUser) {
              _this.messages.push(data);
              // 构建消息内容
              _this.createContent(data.from, null, data.text);
            }
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        };
      }
    },
    tohuman(){
      this.human = true;
      this.$message.success('已转人工客服');
    }
  },
};
</script>